package org.compiere.process;

import java.sql.Timestamp;

import org.adempiere.exceptions.AdempiereException;
import org.compiere.model.Mhrmbusinesstrip;
import org.compiere.model.Mhrmbusinesstripline;
import org.compiere.model.Mhrmemployee;
import org.compiere.model.Mhrmorder;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.eevolution.model.X_HR_Employee;

import extend.org.compiere.utils.Util;

public class GenerateTripSalary extends SvrProcess {

	private Timestamp dateFrom;
	private Mhrmbusinesstrip btrip = null;
	
	/**	Employee List	*/
	private Mhrmemployee[] m_orderlines;
	
	@Override
	protected void prepare() {
		
		btrip = new Mhrmbusinesstrip(getCtx(), getRecord_ID(), null);
	}

	@Override
	protected String doIt() throws Exception {
		dateFrom = btrip.getDateFrom();
		//
		Mhrmorder vorder = new Mhrmorder(getCtx(), btrip.gethrm_order_ID(), null);
		m_orderlines = vorder.getLinesEmployee();
		for(int i=0; i < m_orderlines.length; i++){
			X_HR_Employee hremp = X_HR_Employee.getHR_Employee(m_orderlines[i].getC_BPartner_ID(),true);
			if (hremp.getC_BPartner_ID() == 0)
				throw new AdempiereException ("Info about employee was empty");
			Mhrmbusinesstripline btline = Mhrmbusinesstripline.getBTripline(hremp.getC_BPartner_ID(), dateFrom);
			if(btline == null)
				btline = new Mhrmbusinesstripline (Env.getCtx(), 0, null);
			
			btline.sethrm_businesstrip_ID(btrip.gethrm_businesstrip_ID());
			btline.setC_BPartner_ID(hremp.getC_BPartner_ID());
			btline.setHR_Department_ID(hremp.getHR_Department_ID());
			btline.setHR_Job_ID(hremp.getHR_Job_ID());
			btline.setStartDate(vorder.getStartDate());
			btline.setEndDate(vorder.getEndDate());
			btline.sethrm_businesstriptype(vorder.gethrm_businesstriptype());
			int days = Util.getDays(vorder.getStartDate(), vorder.getEndDate()) + 1;
			btline.sethrm_days(days);
			String whereTo = vorder.gethrm_whereto().getName();
			if (vorder.gethrm_whereto1().getName() != null){
				whereTo = whereTo + " - " + vorder.gethrm_whereto1().getName();
				if (vorder.gethrm_whereto2().getName() != null){
					whereTo = whereTo + " - " + vorder.gethrm_whereto2().getName();
					if (vorder.gethrm_whereto3().getName() != null){
						whereTo = whereTo + " - " + vorder.gethrm_whereto3().getName();
						if (vorder.gethrm_whereto4().getName() != null){
							whereTo = whereTo + " - " + vorder.gethrm_whereto4().getName();
			 			}
		 			}
	 			}
				
 			}
			btline.sethrm_whereto(whereTo);					
			btline.saveEx();
		}
		
		return Msg.translate(getCtx(), "Success");
	}

}
